<template>
  <div class="homeBefore">
    <div style="position: relative;width:100%;height:50px;">
      <van-nav-bar
        fixed
        title="大熊贷款"
      />
    </div>
    <van-pull-refresh style="min-height:100%" v-model="isLoading" @refresh="onRefresh" >
      <van-list
        v-model="newsLoading"
        :finished="newsFinished"
        @load="newsOnLoad"
      >
        <div v-if="((!orderNo)||step==61)&&remainingDays==null" style="overflow:hidden">
          <van-swipe class="my-swipe" :autoplay="3000" indicator-color="#43A4FF" >
            <van-swipe-item v-for="(item,index) in adDate" :key="index">
              <!-- :href="item.targetPath" -->
              <a @click="aHref(item.targetPath,item.title)" ><img width="100%" height="100%" :data-id="item.id" :src="item.imgPath" :alt="item.title"></a>
            </van-swipe-item>
          </van-swipe>
          <div class="core-function">
            <div v-if="step==10">
              <div class="hint" v-if="pageTopRollTipList.length>0">
                <i class="iconfont icon-laba"></i>
                <van-swipe class="carousel" :autoplay="3000" vertical :show-indicators="false" :width="250" :height="30">
                  <van-swipe-item class="carousel-item" v-for="(item,index) in pageTopRollTipList" :key="index">
                    {{item.tip}}</van-swipe-item>
                </van-swipe>
              </div>
              <p class="maximum">最高额度 （元）</p>
              <div class="msg-box">
                <p class="num">20000</p>
              </div>
              <div class="apply-for" @click="applyFor">立即申请</div>
            </div>
            <div v-if="step!=10">
              <p class="Certification-status">{{statusTitle}}</p>
              <p class="supplement">赶快完善剩余信息，加快放款进度~</p>
              <div class="apply-for" @click="applyFor">继续补充</div>
            </div>
          </div>
        </div>
        <!-- 审核中或审核失败 -->
        <!-- <div ></div> -->
        <div class="audit" v-if="(orderNo&&step!=61)||remainingDays!=null">
          <div class="header">
            <div class="audit-in" v-if="step==1">
              <img class="icon" src="../../../assets/chuli.png" alt="" />
              <p class="InTheReview">审核中，您的资料已提交，请等待</p>
              <p class="header-hint">审核结束后，我们将在第一时间短信通知您，请务必保持手机开机。</p>
            </div>
            <div class="audit-error" v-if="step==-1">
              <p class="InTheReview">非常抱歉，审核未通过</p>
              <p class="header-hint">建议您保持良好的信用记录,<span style="color:#FF8024">{{remainingDays}}天</span>之后可以重新申请</p>
            </div>
          </div>
          <!-- 贷款超链接 -->
          <van-row class="good-app" v-if="loanAppList.length>0">
            <van-row>
              <van-col class="head-tit recommend" span="24" v-if="step==-1">为您精选以下平台，大幅提高成功率</van-col>
              <van-col class="head-tit text-left" span="24" v-if="step==1"><i></i>优质贷款推荐</van-col>
            </van-row>
            <van-row class="app-list" type="flex" justify="space-around">
                <div class="item" :data-channelId="item.channelId||'-1'" v-for="(item,index) in loanAppList" :key="index" @click="loanAppClick(item.id,item.targetPath,item.name)">
                  <img class="app-ico" :src="item.icon"  />
                  <div class="app-details">
                    <span class="name">{{item.name}}</span>
                    <span class="keywords">{{item.subtitleTitle}}</span>
                    <div class="people-num van-ellipsis">{{item.applyPeopleNum}}人已申请成功</div>
                  </div>
                </div>
            </van-row>
          </van-row>
          <!-- 热门资讯 -->
          <van-row class="hot-information" v-if="loanAppList.length==0">
            <van-row>
              <van-col class="head-tit text-left" span="24"><i></i>热门资讯</van-col>
            </van-row>
            <van-row class="news-list">
                <div class="item" v-for="(item, index) in newsList" :key="index" @click="newsDetails(item.targetPath,item,title)">
                  <div class="left-title text-left">
                    <div>{{item.title}}</div>
                    <p>{{item.createTime}}</p>
                  </div>
                  <img class="right-img" :src="item.imgPath" alt="" >
                </div>


            </van-row>

          </van-row>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
  import { Swipe, SwipeItem, Toast,Row ,Col ,List ,Dialog ,NavBar, PullRefresh } from 'vant';
// import { clearInterval } from 'timers';
  var  timer=0;
  export default {
    components: {
      [Swipe.name]:Swipe,
      [SwipeItem.name]:SwipeItem,
      [Toast.name]:Toast,
      [Row.name]:Row,
      [Col.name]:Col,
      [List.name]:List,
      [Dialog.name]:Dialog,
      [NavBar.name]:NavBar,
      [PullRefresh.name]:PullRefresh,
    },
    data(){
      return{
        // Carousel:true,//
        token:'',
        isLogin:false, //是否登录
        disable:true,//按钮禁用
        step:'10',//贷款进度
        orderNo:'',//订单号，判断当前状态
        statusTitle:'实名认证已通过',
        adDate:'',//广告list
        pageTopRollTipList:[],//信息轮播list
        loanAppList:[],//贷款app列表
        deviceNo:'123',//设备号
        newsRoloanApp:true, //展示loanapp或者新闻
        newsList: [],//新闻列表
        newsLoading: false,//新闻loading状态
        newsFinished: false,//新闻底部加载状态
        newsPageNum:1,//新闻当前页数
        isLoading:false,
        remainingDays:null,//重新申请时间
        _hmtState:true //统计状态
      }
    },
    destroyed(){
      if(timer) { //如果定时器在运行则关闭
          clearInterval(timer);
      }
    },
    mounted(){
      _hmt.push(['_trackPageview', '/HomeBefore']);
      this.$util.goBack(Dialog,'false');
      Toast.loading({duration:1000,mask: false,message: '加载中...'});
      let _this = this;
      // 获取本地数据
      this.$util.getUser().then(token=>{
        _this.token=token;
        _this.ad();
        _this.pageTopRollTip();
        _this.newsData(1,5)
        _this.loanList();
        // _this.loginState();
        if(token!='-1'){
          _this.isLogin=true;
          _this.myinfo(token);
          _this.$util.appVersion(token,Dialog)
          //检查是否是三方认证返回的
          let desc = _this.$util.getUrlKey('desc');
          console.log(desc)
          if(desc == '认证申请失败'){
            Toast('认证申请失败')
            _this.borrowBeforeSchedule();
          }else if(desc == '认证申请失败,工单不存在'){
            Toast('认证申请失败,工单不存在')
            _this.borrowBeforeSchedule();
          }else if(desc == '认证申请成功?all_submit=1'){
            // 认证成功保存
            if(!_this.$util.getSaveVlues('desc')==1){
              _this.saveOperatorAuthStatus();
            }else{
              _this.borrowBeforeSchedule();
            }
          }else{
            _this.borrowBeforeSchedule();
          }
        }else{
          // this.$router.push({ path: '/login'})
        }

      })
    },
    methods: {
      aHref(url,title){
        this.$util.nativeHeader(url,title)
      },
      // 下拉刷新
      onRefresh(){
        this.borrowBeforeSchedule('onRefresh')
      },
      // header广告
      ad(){
        let _this = this;
        this.$api.get('/ad/v1/list?adGroupCode=homeHead&pageNum=1&pageSize=10',{},s=>{
          _this.adDate = s.module.list;
        },f=>{
          Toast(f.errorMessage)
        },{
          'Accept': 'application/json',
          'channelCode':this.$util.channelCode,
          'version':this.$util.version,
          'token':this.token
        })
      },
      //文字广告
      pageTopRollTip(){
        let _this = this;
        this.$api.get('/sys/v1/pageTopRollTip',{},s=>{
          _this.pageTopRollTipList = s.module;
        },f=>{
          Toast(f.errorMessage)
        },{
          'Accept': 'application/json',
          'channelCode':this.$util.channelCode,
          'version':this.$util.version,
          'token':this.token
        })
      },
      // 进度查询
      borrowBeforeSchedule(onRefresh){
        let _this = this;
        clearInterval(timer)
        this.$api.get('/borrowBefore/v1/borrowBeforeSchedule?bankrollCode='+this.$util.bankrollCode,{},s=>{
          console.log(s);
          if(onRefresh){
            Toast('刷新成功');
            _this.isLoading = false;
          }
          _this.step = s.module.step;

          _this.orderNo = s.module.orderNo;
          _this.remainingDays =  s.module.remainingDays;
          // _this.step = -1;
          // _this.orderNo = 1;
          //初始化页面
          if(s.module.step!=10&&s.module.step!=61){
            _this.statusTitle = '实名认证已通过'
          }else {
            _this.statusTitle = '运营商认证失败'
          }
          if(_this.orderNo){
            // _this.newsData(1,10);
            _this.loanList();
          }
          // 审核中定时刷新页面更新状态
          if(_this.step==1||_this.step==-1){
            if(_this.step==1&&_this._hmtState){
              _this._hmtState = false;
              _hmt.push(['_trackPageview', '/dqsh']);
            }else if(_this.step==-1&&_this._hmtState){
              _this._hmtState = false;
              _hmt.push(['_trackPageview', '/rejected']);
            }
            timer=setInterval(() => {
              _this.borrowBeforeSchedule();
              _this.myinfo(this.token);
            }, 5000)
          }

        },f=>{
          if(onRefresh){
            Toast('刷新成功');
            _this.isLoading = false;
          }else{
            if(f.resultCode=='10003'||f.resultCode=='10000'||f.resultCode=='10001'||f.resultCode=='10002'){
              _this.isLogin = false;
            }else{

              Toast(f.errorMessage)
            }
          }
        },{
          'Accept': 'application/json',
          'channelCode':this.$util.channelCode,
          'version':this.$util.version,
          'token':this.token
        })
      },
      //新闻 /news/v1/list
      newsData(pages,num){
        let _this = this ;
        let newsGroupCode = 'dxdkapp';
        let newsList = _this.newsList
        this.$api.get('/news/v1/list?newsGroupCode='+newsGroupCode+'&pageNum='+pages+'&pageSize='+num,{},s=>{
          console.log(s);
          let arr = s.module.list;
          if(arr.length != num){
            _this.newsFinished = true;
          }else{
            _this.newsPageNum++;
          }
          for(var i=0;i<arr.length;i++){
            newsList.push(arr[i]);
          }
          _this.newsList = newsList;
          // 加载状态结束
          _this.newsLoading = false;
          },f=>{

        },{
          'Accept': '*/*',
          'Content-Type':'application/json',
          'channelCode':this.$util.channelCode,
          'version':this.$util.version,
          'token':this.token
        })
      },
      newsOnLoad() {
        console.log(312)
        let newsPageNum = this.newsPageNum;
        if(newsPageNum>1){
          this.newsData(newsPageNum,5)
        }
      },
      newsDetails(url,title){
        // window.location.href = url
        this.$util.nativeHeader(url,'热门资讯')
      },
      //app列表/loan/v1/list
      loanList(){
        let _this =this;

        let loanGroupCode = 'dqshdc';
        if(this.step == '61'||this.step == '-1'){
          loanGroupCode = 'dqbjdc';
        }
        this.$api.get('/loan/v1/list?loanGroupCode='+loanGroupCode,{},s=>{
            console.log(s);
            _this.loanAppList = s.module;
          },f=>{
            Toast(f.errorMessage);
        },{
          'Accept': '*/*',
          'Content-Type':'application/json',
          'channelCode':this.$util.channelCode,
          'version':this.$util.version,
          'token':this.token
        })
      },
      loanAppClick(id,url,title){
        let _this =this;
        this.$api.post('/loan/v1/click?loanID='+id+'&deviceNo='+this.deviceNo,{},s=>{
            console.log(s);
          },f=>{
            Toast(f.errorMessage);
        },{
          'Accept': '*/*',
          'Content-Type':'application/json',
          'channelCode':this.$util.channelCode,
          'version':this.$util.version,
          'token':this.token
        })
        // window.location.href = url
        this.$util.nativeHeader(url,title)
      },
      //认证资料
      applyFor(){
        console.log(this.step)
        if(!this.isLogin){
          this.$util.url('/login','登录')
          return false;
        }
        // 10=未开始，20=基本信息已经完成，30=联系人信息已经完成，40=身份证认证已经完成，50=人脸认证已经完成，60=运营商认证已经完成，61=运营商认证失败/过期，1=审核中，-1=审核未通过，0=审核通过
        switch (this.step) {
          case 10:
            //未开始，跳转 基本信息
            this.$util.url('/basicInfo','基本信息')
            // this.$router.push({ path: '/basicInfo'})
            break;
          case 20:
            //基本信息完成，跳转 联系人信息
            this.$util.url('/contactInfo','联系人信息')
            // this.$router.push({ path: '/contactInfo'})
            break;
          case 30:
            //联系人信息完成，跳转 身份证认
            this.$util.url('/identityInfo','身份信息')
            // this.$router.push({ path: '/identityInfo'})
            break;
          case 40:
            //身份证认完成，跳转 人脸认证
            this.$util.url('/FaceRecognition','人脸识别')
            // this.$router.push({ path: '/FaceRecognition'})
            break;
          case 50:
            //人脸认证完成，跳转 运营商认证
            // 三方页面
            this.applyBorrowMoney()
            break;
          case 60:
            // 全部完成怎么跳转？
            break;
          case 61:
          // 重新认证
          //
            this.AuthOrderNo()
            break;

          default:
            break;
        }
      },
      AuthOrderNo(){
        let _this =this;
        this.$api.post('/borrowBefore/v1/generateOperatorAuthOrderNo?bankrollCode='+this.$util.bankrollCode,{},s=>{
            console.log(s);
            let orderNo = s.module;
            _this.$util.h5Authenticate(orderNo)
          },f=>{
            Toast(f.errorMessage);
        },{
          'Accept': '*/*',
          'Content-Type':'application/json',
          'channelCode':this.$util.channelCode,
          'version':this.$util.version,
          'token':this.token
        })
      },
      //进件获取订单号
      applyBorrowMoney(){
        let _this = this;
        Toast.loading({duration:500,mask: false,message: '加载中...'});
        this.$api.post('/borrowBefore/v1/applyBorrowMoney?bankrollCode='+this.$util.bankrollCode,{},s=>{
          console.log(s)
          let orderNo = s.module.orderNo;
          _this.$util.h5Authenticate(orderNo);
        },f=>{
          if(f.resultCode=='20005'){
            // 表示进件失败，对方拒绝我们,直接展示拒绝页面，这里需要修改下列参数，调下面接口
            _this.step = -1;
            _this.remainingDays = 7;
            _this.orderNo=-1;
            // _this.newsData(1,10);
            // _this.loanList();
          }else if(f.resultCode=='20007'){
            // _this.generateOperatorAuthOrderNo()
          }else if(f.resultCode=='20012'){
            Toast('获取三方认证失败，请重试！');
          }else if(f.resultCode=='20013'){
            Toast('审核失败');
            _this.$util.url('/HomeBefore','首页')
          }else{
            Toast(f.errorMessage);
          }
        },{
          'Content-Type': 'application/json',
          'Accept': "*/*",
          'channelCode':this.$util.channelCode,
          'version':this.$util.version,
          'token':this.token
        })
      },
      // 认证成功，保存进度
      saveOperatorAuthStatus(){
        let _this = this ;
        this.$api.post('/borrowBefore/v1/saveOperatorAuthStatus?bankrollCode='+this.$util.bankrollCode,{},s=>{
            console.log(s);
            // 查询进度
             _this.$util.setSaveVlues('desc','1')
            _this.borrowBeforeSchedule();
          },f=>{
            if(f.resultCode =='20021'){
              // 当前不允许发起运营商认证，请重试！
              _this.borrowBeforeSchedule();
            }else if(f.resultCode =='10003'||f.resultCode =='10000'||f.resultCode=='10001'||f.resultCode=='10002'){

            }else{
              Toast(f.errorMessage);
            }
        },{
          'Accept': '*/*',
          'Content-Type':'application/json',
          'channelCode':this.$util.channelCode,
          'version':this.$util.version,
          'token':this.token
        })
      },
      myinfo(token){
        let _this = this;
        this.$api.post('/user/v1/info',{},s=>{
          console.log(s);
          _this.info = s.module;
          if(s.module.loanSchedules[0].state == 20){
            _this.$util.url('/HomeIn','首页')
          }
        },f=>{
          if(f.resultCode =='10003'||f.resultCode =='10000'||f.resultCode=='10001'||f.resultCode=='10002'){
            _this.isLogin=false;
          }else{
            Toast(f.errorMessage);
          }
        },{
          'Accept': 'application/json',
          'channelCode':this.$util.channelCode,
          'version':this.$util.version,
          'token':token
        })
      }
    }

  }
</script>

<style>
.van-swipe{
  overflow:inherit ;
}
/* .van-swipe__indicators {
    bottom:20px
} */
</style>
<style scoped lang="scss">
.homeBefore{
  // width:275px;
  width:100%;
  height:100%;
  font-size:0.28rem;
}
.my-swipe{
    overflow: hidden;
    width:349px;
    height:130px;
    border-radius:15px;
    margin:13px auto;
    box-shadow: 0px 0px 10px 2px #E6E6E6;
}
.core-function{
    position:relative;
    display:flex;
    flex-direction: column;
    align-items:center;
    width:349px;
    height:248px;
    margin:30px auto 10px;
    border-radius:8px;
    box-shadow: 0px 0px 10px 2px #E6E6E6;
  }
  .hint{
    position:absolute;
    left:0;
    top:0;
    width:100%;
    display: flex;
    flex-direction: row;
    justify-content:center;
    align-items: center;
    margin-top:15px;
    line-height:20px;
    font-size:12px;
    color:#41424E;
  }
  .hint i{
    position:relative;
    top:-3px;
  }
  .icon-laba:before {
    position:relative;
    top:5px;
    margin-left:-10px;
    font-size:25px;
    color:#FF8024
   }
   .maximum{
     font-size:12px;
     line-height:30px;
     margin-top:62px;
     color:#41424E;
   }
   .msg-box{
     height:80px;
   }
   .num{
     font-size:55px;
     font-weight:600;
     line-height:50px;
     color:#1D0F00;
   }
   .timer{
     color:red;
   }
   .apply-for{
     width:239px;
     height:46px;
     line-height:46px;
     font-size:16px;
     border-radius:15px;
    background:#FF8024;
     color:#fff;
   }
   .carousel{
     overflow: hidden;
     width:250px;
     height:30px;
     margin-top:2px;
     margin-left:-3px;
     line-height: 30px;
   }
   .Certification-status{
     margin-top:70px;
     font-size:22px;
     font-weight: 600;
      color:#1D0F00;
   }
   .supplement{
      margin-top:20px;
      margin-bottom:30px;
     font-size:14px;
      color:#797A79;
   }
// 审核中样式
  .header{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    // height:220px;
    height:150px;
    background: #fff;
  }
  .audit-in{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .audit-error{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .icon{
    width:90px;
    height:73px;
  }
  .InTheReview{
    padding:0 30px;
    margin-top:10px;
    text-align: left;
    font-size:15px;
    font-weight: 600;
    color:#333;
  }
  .header-hint{
    margin-top:25px;
    font-size:14px;
    text-align: left;
    color:#797A79;
  }
   .audit{
     padding: 0 0.4rem;
   }
   .good-app{
    padding:21px 0;

    .head-tit{
      height:20px;
      font-size:14px;
      line-height: 20px;
      color:#1D0F00;
      &.recommend{
        height:30px;
        line-height: 30px;
        font-weight: 600;
        background: #FFEC9C;
        color:#41424E;
      }
      i{
        position:relative;
        top:2px;
        display: inline-block;
        width:4px;
        height:13px;
        margin-left:3px;
        margin-right:4px;
        border-radius: 20px;
        background:#FF8024;
      }
    }
    .app-list{
      margin-top:15px;
      padding-top:10px;
      // justify-content: flex-start;
      flex-wrap:wrap;
      justify-content: flex-start;
      // max-height:380px;
      overflow-y:scroll;
      // overflow-x:auto;
      white-space: nowrap;
      /*解决ios上滑动不流畅*/
      -webkit-overflow-scrolling: touch;
      /*利用padding将滚动条挤出：纵向超出部分将会隐藏，即滚动条部分被挤出可视区域*/
      padding-bottom: 20px;
      .item{
        // width:169px;
        display:flex;
        flex-direction: row;
        width:154px;
        height:80px;
        margin:0 5px 10px;
        background: #fff;
        box-shadow: 0 1px 5px 0 rgba(186,186,186,0.50);
        border-radius: 4px;
      }
      .app-ico{
        width:30px;
        height:30px;
        margin:10px 8px 0 10px;
      }
      .app-details{
        display: flex;
        flex-direction: column;
        width:106px;
        text-align: left;
        margin-top:10px;
      }
      .app-details .name{
        font-size:14px;
        line-height: 20px;
        color:#1D0F00;
      }
      .app-details .keywords{
        font-size:12px;
        line-height: 17px;
        color:#1D0F00;
      }
      .app-details .people-num{
        margin-top:8px;
        font-size:12px;
        line-height: 17px;
        color:#797A79;
      }
    }
  }
  .hot-information{
    padding:21px 0;
    .head-tit{
      height:20px;
      font-size:14px;
      line-height: 20px;
      color:#1D0F00;
      i{
        position:relative;
        top:2px;
        display: inline-block;
        width:4px;
        height:13px;
        margin-left:3px;
        margin-right:4px;
        border-radius: 20px;
        background:#FF8024;
      }
    }
    .news-list{
      // margin-top:15px;
      padding-top:10px;
      justify-content: flex-start;
      flex-wrap:wrap;
      // height:380px;
      overflow-y:scroll;
      // white-space: nowrap;
      /*解决ios上滑动不流畅*/
      -webkit-overflow-scrolling: touch;
      /*利用padding将滚动条挤出：纵向超出部分将会隐藏，即滚动条部分被挤出可视区域*/
      padding-bottom: 20px;
      .item{
        overflow: hidden;
        display: flex;
        flex-direction: row;
        width:100%;
        border-bottom:1px solid #E6E6E6;
        // height:80px;
        padding:10px 0;
      }
      .left-title{
        flex:1;
        div{
          overflow:hidden;
          width:237px;
          height:40px;
          font-size:14px;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          color:#41424E;
        }
        p{
          line-height: 30px;
          font-size:14px;
          color:#797A79;
        }
      }
      .right-img{
        width:90px;
        height:70px;
        background:#ccc;
      }
    }
  }
</style>